package 线程池.CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/4/24 13:55
 * @description:使用多线程的回调和感知异常，handle() 是一个绝佳的选择
 * @version:
 */
public class ShowThread4 {
    //创建线程池  第一个参数代表核心线程数
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main....start....");

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("运行结果：" + i);
            return i;
        }, executor).handle((res,exception) -> {
            //方法完成后的处理：handle()
            if(res != null){
                //如果res不等空，说明有返回结果（这里只是演示，正常情况下可以直接将res返回出去或者经过处理再返回出去）
                return  res * 2;
            }
            if(exception != null){
                //说明出现异常了
                return 0;
            }
            return 0;
        });
        //获取返回值，也是阻塞式等待
        Integer integer = future.get();
        System.out.println("返回结果" + integer);
        System.out.println("main....end....");
        executor.shutdown();
    }
}
